import { shallowRef } from 'vue'
import {
  setToken,
  setUserInfo,
  setMenuCollapseStatus,
  getToken,
  getUserInfo,
  getMenuCollapseStatus,
  clearAll
} from '@/utils/storage'
import { httpGet, httpPost } from '@/utils/request'
import router from '@/router'
import localMenus from './router/local.routes'

export const signToken = shallowRef(getToken())
export const isCollapse = shallowRef(getMenuCollapseStatus())
export let userInfo = getUserInfo()
export let menuTree = []

export function fetchMenusByUser() {
  return new Promise(resolve => {
    setTimeout(async () => {
      // 后端路由
      // try {
      //     const resp = await httpPost('/smart/am-system-menu2/listAllForTreeOfCurrentUser')
      //     menuTree = resp.data
      //     resolve(resp.data)
      // } catch (e) {
      //     console.log(e);
      // }
      menuTree = localMenus
      resolve(localMenus)
    }, 100)
  })
}

//actions

export function toggleCollapse() {
  isCollapse.value = !isCollapse.value
  setMenuCollapseStatus(isCollapse.value)
}

export async function login(data) {
  const resp = await httpGet('/login', data)
  const { token, current_user } = resp.data
  signToken.value = token
  setToken(token)
  userInfo = current_user
  setUserInfo(current_user)
  const [firstRoute] = await fetchMenusByUser()
  await router.replace(firstRoute.path)
  return Promise.resolve()
}

export async function logout() {
  await httpGet('/logout')
  clearAll()
  router.replace('/login')
  location.reload()
  return Promise.resolve()
}
